package com.abcode.test.springbootmybatisplus.gen.controller;

import cn.hutool.core.collection.CollUtil;
import com.abcode.test.springbootmybatisplus.gen.common.Result;
import com.abcode.test.springbootmybatisplus.gen.entity.UserDetailsInfo;
import com.abcode.test.springbootmybatisplus.gen.nick.AINicknameCollection;
import com.abcode.test.springbootmybatisplus.gen.nick.UserConfigLoader;
import com.abcode.test.springbootmybatisplus.gen.service.UserDetailsInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/gen/nickName")
public class NickNameController {

    @Resource
    private UserDetailsInfoService userDetailsInfoService;
    @Resource
    private UserConfigLoader userConfigLoader;

    @GetMapping("/createNickName")
    public Result<List<String>> createNickName() {
        List<String> nicknames = AINicknameCollection.getRandomNicknames(1000);
        return Result.ok(nicknames);
    }

    // 更改机器人昵称
    @GetMapping("/updateNickName")
    public Result<String> updateNickName() throws IOException {
        // 获取配置的机器人ID
        Set<String> robotIds = userConfigLoader.getAllUniqueUserIds();

        // 查询数据库所有的机器人
        LambdaQueryWrapper<UserDetailsInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(UserDetailsInfo::getUserId, robotIds);
        List<UserDetailsInfo> userList = userDetailsInfoService.list(lambdaQueryWrapper);
        if (CollUtil.isEmpty(userList)) {
            return Result.error("没有机器人");
        }

        // 生成昵称
        List<String> nicknames = AINicknameCollection.getRandomNicknames(userList.size());

        List<UserDetailsInfo> udpateList = new ArrayList<>();
        for (int i = 0; i < userList.size(); i++) {
            UserDetailsInfo user = userList.get(i);
            UserDetailsInfo updateUser = new UserDetailsInfo();
            updateUser.setUserId(user.getUserId());
            updateUser.setOldNikeName(user.getNikeName());
            updateUser.setNikeName(nicknames.get(i));
            udpateList.add(updateUser);
        }
        if (CollUtil.isNotEmpty(udpateList)) {
            userDetailsInfoService.updateBatchById(udpateList);
            log.info("|updateNickName|更新机器人昵称成功: {}", udpateList.size());
        } else {
            log.info("|updateNickName|没有需要更新的数据");
        }
        return Result.ok("更新成功");
    }
}
